<template>
  <!--车站选择下拉框-->
  <a-select v-model:value="stationName" show-search allowClear
            :filterOption="filterStationNameOption"
            @change="onChange" :placeholder="placeholder || '请选择车站'"
            :style="'width: ' + localWidth">
    <a-select-option v-for="item in stations" :key="item.name" :value="item.name"
                     :label="item.name + item.namePinyin + item.namePy">
      {{ item.name }} | {{ item.namePinyin }}
    </a-select-option>
  </a-select>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue';
import request from "@/utils/request";
import {notification} from "ant-design-vue";

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: String,
  width: String,
  placeholder: String
})
// 车站名称
const stationName = ref();
// 车站列表
const stations = ref([]);
// 下拉框宽度，默认 65%
const localWidth = ref(props.width || "65%");

// 利用watch，动态获取父组件的值(v-model)，如果放在onMounted或其它方法里，则只有第一次有效
watch(() => props.modelValue, () => {
  stationName.value = props.modelValue;
}, {immediate: true});

// 查询所有的车站，用于车站下拉框
const queryAllStation = () => {
  // 先从缓存中获取，如果没有再发起请求
  let cache = SessionStorage.get(SESSION_SELECT_STATION)
  if (Tool.isNotEmpty(cache)) {
    stations.value = cache;
  } else {
    request.get("/business/station/all")
        .then(result => {
          if (result.status) {
            stations.value = result.content;
            SessionStorage.set(SESSION_SELECT_STATION, stations.value)
          } else {
            notification.error({description: result.message});
          }
        });
  }
};

// 车站下拉框筛选
const filterStationNameOption = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 将当前组件的值响应给父组件
const onChange = (value) => {
  emit('update:modelValue', value);
  let station = stations.value.filter(item => item.code === value)[0];
  if (Tool.isEmpty(station)) station = {};
  emit('change', station);
};

onMounted(() => {
  queryAllStation();
});
</script>
